package com.navi.loaddata.loadService.impl.baseData;

import com.navi.loaddata.core.errorLog.ErrorCode;
import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.gpEntity.MArrayParamD;
import com.navi.loaddata.core.gpEntity.MOpeD;
import com.navi.loaddata.core.gpEntity.MParamD;
import com.navi.loaddata.core.mesEntity.MesProducthistory;
import com.navi.loaddata.core.mesEntity.MesProductspec;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.oracleEntity.EtlProductV;
import com.navi.loaddata.core.oracleEntity.EtlStepV;
import com.navi.loaddata.core.repository.impl.GreenPlumRepositoryImpl;
import com.navi.loaddata.core.repository.impl.MesRepositoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.navi.loaddata.core.constant.GenericDef.OTHER;
import static com.navi.loaddata.core.constant.GenericDef.SHOP_OC;

@Service
@Transactional(transactionManager = "mesPlatformTransactionManager",
        rollbackFor = {RuntimeException.class, Exception.class})
public class LoadMesBaseDataService {

    @Autowired
    private MesRepositoryImpl daomes;
    @Autowired
    private GreenPlumRepositoryImpl dao2;
    @Autowired
    private ProcessBaseDataService processBaseDataService;
    private static final Logger logger = LoggerFactory.getLogger(LoadMesBaseDataService.class);

    //STEP
    public List<EtlStepV> loadAllFinalStep(String shopId) throws Exception {
        List<EtlStepV> etlStepV = new ArrayList<>();
        List<MOpeD> stepList = new ArrayList<>();
        String hql = "from MOpeD where ope_id is not null and ope_id <>'' and shopId='" + shopId + "' and validFlg='Y'";

        try {
            stepList = dao2.find(MOpeD.class, hql);
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_GET_GP_STEP, e);
        }
        try {
            etlStepV = processBaseDataService.processStep(stepList);
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_PROCESS_GP2ORA_STEP, e);
        }
        return etlStepV;
    }


    //PRODUCT
    /*
根据DPG文件所定。以A1495A1ANK1为例。
item5	MODEL_NAME	Varchar2(32)	495A1
item6	PANEL_SIZE	Varchar2(32)	495
        将现行同步product_t的item5/6逻辑修改为：ARRAY/CF/CELL/CELL2 的product_ID 以A/C/L开头 截取3-7 为item5，截取3-5码为 item6。请协助配合修改！
此外
1、ARRAY/CF 的productid长度为11码。以A/C开头！其余不同步。
2、CELL/CELL2的productid长度为14码，以A/C/L开头。其余不同步。
3、bounding后的productid为10码。product_t的item5/6。截取2-6 为item5。 截取2-4码为 item6。(参考CHOT naming rule文件)
 */
    public List<EtlProductV> loadAllFinalProduct(String shopId) throws Exception {
        List<MesProductspec> mesProductspecList = new ArrayList<>();
        List<EtlProductV> etlProductVList = new ArrayList<>();
        Map<String, Boolean> productMap = new HashMap<>();

        String hql = "from MesProductspec where PRODUCTIONTYPE IN ('Engineer','Production') ";
        if (!StringUtils.isEmpty(shopId)) {
            hql += " and subfactoryname = '" + shopId + "'";
        }
        if ("ARRAY".equals(shopId) || "CF".equals(shopId)) {
            hql += " and LENGTH(PRODUCTSPECNAME)=11 and (PRODUCTSPECNAME LIKE 'A%' OR PRODUCTSPECNAME LIKE 'C%')";
        } else if ("OC".equals(shopId)) {
            hql += " and LENGTH(PRODUCTSPECNAME) in(10,14)";
        }
        try {
            mesProductspecList = daomes.find(MesProductspec.class, hql);
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_GET_GP_PRODUCT, e);
        }

        try {
            mesProductspecList.forEach(p -> {
                String productName = p.getProductspecname();
                if (null == productMap.get(productName)) {
                    productMap.put(productName, true);

                    EtlProductV etlProductV = new EtlProductV();
                    etlProductV.setProductId(p.getProductspecname());
                    etlProductV.setProductVersion("00001");
                    String productGroup = OTHER;
                    if ("A".equals(p.getProductspecname().substring(0, 1)) || "C".equals(p.getProductspecname().substring(0, 1)) || "L".equals(p.getProductspecname().substring(0, 1))) {
                        productGroup = p.getProductspecname().substring(2, 7);
                    } else {
                        productGroup = p.getProductspecname().substring(1, 6);
                    }
                    etlProductV.setProductGroup(productGroup);
                    etlProductV.setModelName(productGroup);
                    etlProductV.setPanelSize(productGroup.substring(0, 3));
                    etlProductV.setProductType(p.getProductiontype());
                    etlProductV.setPanelQty(p.getProductquantity());
                    etlProductV.setProductIdErp(p.getErpproductspecname());

                    etlProductVList.add(etlProductV);
                }
            });
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_PROCESS_GP2ORA_PRODUCT, e);
        }
        return etlProductVList;
    }


    public List<MesProducthistory> loadCommonGlassInfo(EtlConfDModel etlConfD, String glassId) {
        List<MesProducthistory> mesProducthistoryEntity = new ArrayList<>();
        try {
            StringBuffer hql = new StringBuffer();
            hql.append("FROM MesProducthistory WHERE subfactoryname='").append(etlConfD.getShop()).append("' ")
                    .append(" and PRODUCTNAME ='").append(glassId).append("' AND ROWNUM=1 ORDER BY TIMEKEY DESC");//取最新一笔，因为产品可能有变化
            List<MesProducthistory> allCmn = new ArrayList<>();
            allCmn = daomes.list(MesProducthistory.class, hql.toString());
            if (allCmn.size() == 0) {
                throw new ETLException2(ErrorCode.ERROR_GET_MES_HIS_CMN_GLASS, null);
            }
            mesProducthistoryEntity.add(allCmn.get(0));
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_GET_MES_HIS_CMN_GLASS, e);
        }
        return mesProducthistoryEntity;
    }

    public List<MParamD> loadParamInfo2(String shopId) {
        List<MParamD> mParamDList = new ArrayList<>();
        try {
            StringBuffer hql = new StringBuffer();
            hql.append("FROM MParamD where validFlg='Y' and shopName='").append(shopId).append("' and  paramCollection<>'' and  paramCollection is not null");
            List<MParamD> mParamDS = dao2.list(MParamD.class, hql.toString());
            for (MParamD m : mParamDS) {
                mParamDList.add(m);
            }
        } catch (Exception e) {
            throw new ETLException2(ErrorCode.ERROR_GET_GP_PARAM, e);
        }
        return mParamDList;
    }

}
